package com.codingapi.p2p.server.service.impl;

import com.codingapi.p2p.server.handler.DiscardServerHandler;
import com.codingapi.p2p.server.service.InitService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;



/**
 * create by lorne on 2018/3/13
 */
@Service
public class InitServiceImpl implements InitService,DisposableBean {

    @Value("${socket.port}")
    private int port;

    private Logger logger = LoggerFactory.getLogger(InitServiceImpl.class);

    private  EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Override
    public void start() {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();

                            p.addLast(new DiscardServerHandler());
                        }
                    });
            b.bind(port);

            logger.info("netty- listener ! ");

        }catch (Exception e){
            close();
        }
    }

    @Override
    public void close() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();

        logger.info("netty- close ! ");
    }

    @Override
    public void destroy() throws Exception {
        close();
    }
}
